package com.hbmcc.heshenghuo.weight

import android.content.Context
import android.content.res.TypedArray
import android.graphics.Canvas
import android.graphics.Path
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.zhihaoliang.busEncy.R


class RoundImageView(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    AppCompatImageView(context, attrs, defStyleAttr) {
    /**
     * ImageView 宽度
     */
    var width = 0f

    /**
     * ImageView 高度
     */
    var height = 0f

    /**
     * 左上角弧形
     */
    var topLeft = 0f

    /**
     * 右上角角弧形
     */
    var topRight = 0f

    /**
     * 左下角弧形
     */
    var botLeft = 0f

    /**
     * 右下角弧形
     */
    var botRight = 0f


    constructor(context: Context) : this(context, null) {
        initView(null)
    }

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) {
        initView(attrs)
    }

    private fun initView(attrs: AttributeSet?) {
        setLayerType(LAYER_TYPE_SOFTWARE, null)
        val array: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.round_imageview)
        topLeft = array.getDimension(R.styleable.round_imageview_topLeft, 40f)
        topRight = array.getDimension(R.styleable.round_imageview_topRight, 40f)
        botLeft = array.getDimension(R.styleable.round_imageview_botLeft, 40f)
        botRight = array.getDimension(R.styleable.round_imageview_botRight, 40f)
        array.recycle()
    }


    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        width = getWidth().toFloat()
        height = getHeight().toFloat()
    }

    override fun onDraw(canvas: Canvas) {
        val path = Path()
        //四个圆角
        path.moveTo(topLeft, 0f)
        path.lineTo(width - topRight, 0f)
        path.quadTo(width, 0f, width, topRight)
        path.lineTo(width, height - botRight)
        path.quadTo(width, height, width - botRight, height)
        path.lineTo(botLeft, height)
        path.quadTo(0f, height, 0f, height - botLeft)
        path.lineTo(0f, topLeft)
        path.quadTo(0f, 0f, topLeft, 0f)
        canvas.clipPath(path)
        super.onDraw(canvas)
    }

}